package org.apache.guacamole.event;

import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.net.event.AuthenticationFailureEvent;
import org.apache.guacamole.net.event.AuthenticationSuccessEvent;
import org.apache.guacamole.net.event.listener.Listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A Listener implementation intended to demonstrate basic use
 * of Guacamole's listener extension API.
 */
public class TutorialListener implements Listener {

    private static final Logger logger =
            LoggerFactory.getLogger(TutorialListener.class);

    @Override
    public void handleEvent(Object event) throws GuacamoleException {
        System.out.println("handleEvent: " + event.getClass().getCanonicalName());
        if (event instanceof AuthenticationSuccessEvent) {
            var e0 = (AuthenticationSuccessEvent) event;

            System.out.println("AuthenticatedUser: " + e0.getAuthenticatedUser().getClass().getCanonicalName());

//            e0.getAuthenticatedUser().

            var credentials = e0.getCredentials();
            logger.info("successful authentication for user {}", credentials.getUsername());
            logger.info("{}, {}, {}, {}", credentials.getUsername(),
                    credentials.getPassword(),
                    credentials.getRemoteAddress(),
                    credentials.getRemoteHostname());

            var rq = credentials.getRequest();

            var paraNames = rq.getParameterNames();
            while (paraNames.hasMoreElements()) {
                String thisName = paraNames.nextElement().toString();
                String thisValue = rq.getParameter(thisName);
                System.out.println(thisName + " = " + thisValue);
            }

            if (credentials.getSession() != null) {
                paraNames = credentials.getSession().getAttributeNames();
                while (paraNames.hasMoreElements()) {
                    String thisName = paraNames.nextElement().toString();
                    String thisValue = rq.getParameter(thisName);
                    System.out.println("session_" + thisName + " = " + thisValue);
                }
            } else {
                System.out.println("session_is_null.");
            }


        }
        else if (event instanceof AuthenticationFailureEvent) {
            var credentials = ((AuthenticationFailureEvent) event).getCredentials();
            logger.info("failed authentication for user {}", credentials.getUsername());
            logger.info("{}, {}, {}, {}", credentials.getUsername(),
                    credentials.getPassword(),
                    credentials.getRemoteAddress(),
                    credentials.getRemoteHostname());
        }
    }

}